import React from 'react';
import './merchandise.less';
import { Breadcrumb, Button, Table, Pagination, message, Checkbox } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';

const config = new Config();
const token = sessionStorage.getItem('token');
class merchandiseList_zml extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [], // 数据
            title: '', // 标题
            publisher: '', // 发布人
            page: 1, // 当前页
            pageSize: 10, // 每页显示的条数
            total: 0, // 总数
            checkedId: []
        }
        this.InputTitle = this.InputTitle.bind(this)
        this.InputPublisher = this.InputPublisher.bind(this)
        this.onChangePage = this.onChangePage.bind(this)
    }

    componentDidMount() {
        const state = this.props.location.state
        if (state) {
            this.setState({
                page: state.page,
                pageSize: state.pageSize,
                title: state.title,
                describe: state.describe,
            }, () => {
                this.getData()
            })
        } else {
            this.getData()
        }
    }

    //获取产品列表
    getData() {
        const { page, pageSize, title, publisher } = this.state
        $.ajax({
            url: `${config.consultant_gfyy}/productHot/nonHotList`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                page,
                pageSize,
                title,
                publisher,
            },
            success: (res) => {
                console.log('获取产品列表', res)
                if (res.code === 200) {
                    res.data.rows.forEach((item, index) => {
                        item.key = index + 1 + (this.state.page - 1) * this.state.pageSize;
                    })
                    this.setState({
                        total: res.data.count,
                        data: res.data.rows
                    })
                }
            }
        });
    }

    // 表头
    getColumns() {
        return [{
            title: '序号',
            width: '4%',
            dataIndex: 'key'
        }, {
            title: '标题',
            width: '16%',
            dataIndex: 'title'
        }, {
            title: '图片',
            width: '16%',
            render(record) {
                return <p><img src={config.Filepath + record.themeImg} style={{ width: "40px" }} /></p>
            }
        }, {
            title: '介绍',
            width: '16%',
            dataIndex: 'describe'
        }, {
            title: '发布人',
            width: '8%',
            dataIndex: 'publisher'
        }, {
            title: '发布时间',
            width: '10%',
            render(record) {
                return moment(record.createdAt).format('YYYY-MM-DD HH:mm')
            }
        }, {
            title: '分类',
            width: '10%',
            dataIndex: 'classify'
        }, {
            title: '标签',
            width: '8%',
            dataIndex: 'tag'
        }, {
            title: '添加热卖',
            width: '12%',
            render: record => {
                const { page, pageSize, title, publisher } = this.state
                const paths = {
                    pathname: `/merchandise_zml/update`,
                    state: {
                        data: record,
                        page,
                        pageSize,
                        title,
                        publisher
                    }
                }
                return <p>
                    {/* <a href='javascript:void(0)'>修改</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                 */}

                    {/* <Popconfirm title="您确定要删除么？" okText="是" cancelText="否" onConfirm={this.deleteNews.bind(this, record.id)}>
            <a href="javascript:void(0)'">删除</a>
          </Popconfirm> */}
                    <Checkbox
                        onChange={this.handleChange.bind(this, record.id)}
                    >
                        是否热卖
          </Checkbox>

                </p>
            }
        }];
    }

    removeByValue(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == val) {
                arr.splice(i, 1);
                break;
            }
        }
    }

    // 是否选中
    handleChange(id, e) {

        if (e.target.checked) {
            console.log(id, '选中')
            let checkedArray = this.state.checkedId;
            let checkedId = [...checkedArray, id]
            this.setState({
                checkedId
            })
        } else {
            let checkedArray = this.state.checkedId;
            console.log(checkedArray)
            this.removeByValue(checkedArray, id)
            console.log(checkedArray)
            this.setState({
                checkedId: checkedArray
            })
        }
    }



    // 输入搜索值
    InputTitle(e) {
        this.setState({
            title: e.target.value
        });
    }

    // 输入搜索值
    InputPublisher(e) {
        this.setState({
            publisher: e.target.value
        });
    }

    // 搜索/清空
    filterOrders(key) {
        if (key) {
            // 搜索
            this.setState({
                page: 1
            }, () => {
                this.getData();
            });
        } else {
            // 清空
            this.setState({
                page: 1,
                title: '',
                publisher: '',
            }, () => {
                this.getData();
            });
        }
    }

    // 删除产品
    deleteNews(id) {
        $.ajax({
            url: `${config.jusewebsite_gfyy}/product/delete`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: { id },
            success: (res) => {
                console.log('删除产品', res)
                if (res.code === 200) {
                    let { page, data } = this.state
                    if (data.length === 1) {
                        page = page - 1 || 1
                    }
                    this.state.page = page
                    this.getData()
                }
            }
        });
    }

    // 切换分页
    onChangePage(page) {
        this.setState({
            page
        }, () => {
            this.getData();
        });
    }

    addFloor() {
        console.log(this.state.checkedId)
        let productArray = this.state.checkedId;
        if (productArray.length === 0) {
            console.log('未选中任何东西')
            message.error('未选择任何产品', 1)
        } else {
            let productId = productArray.toString();
            console.log(productId)
            $.ajax({
                url: `${config.consultant_gfyy}/productHot/add`,
                type: 'post',
                headers: {
                    'Authorization': 'Bearer ' + token,
                },
                data: { productId },
                success: res => {
                    console.log(res)
                    message.success('添加成功', 1)
                    window.location.hash = `/hot_product_gfyy`
                }
            })
        }
    }
    render() {
        const columns = this.getColumns();
        return (
            <div className='contentBox clearfix'>
                <div className="member-content-Search">
                    <div className='breadcrumb'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>官网管理</Breadcrumb.Item>
                            <Breadcrumb.Item>谷方益元</Breadcrumb.Item>
                            <Breadcrumb.Item>热卖产品</Breadcrumb.Item>
                            <Breadcrumb.Item>新增</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    {/* <div className='orderfilter'>
            <div className="member-content-Search" style={{ marginBottom: 20 }}>
              <div className='addetd' style={{ zIndex: 1 }}>
                <Input addonBefore='标题' placeholder="请输入" value={this.state.title} onChange={this.InputTitle} />
              </div>
              <div className='addetd' style={{ zIndex: 1 }}>
                <Input addonBefore='发布人' placeholder="请输入" value={this.state.publisher} onChange={this.InputPublisher} />
              </div>
              <Button className='ant-btn-primary' icon='search' onClick={this.filterOrders.bind(this, 1)}>搜索</Button>
              <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this, 0)}>重置</Button>
            </div>
          </div> */}
                </div>
                <div className='allgoods-table clearfix'>
                    <Table columns={columns} dataSource={this.state.data} pagination={false} bordered />
                    <div className='goods-label-tabletr'>
                        <Button className='goods-label-table-app' onClick={() => this.addFloor()} icon="plus">保存</Button>
                        <Button className='goods-label-table-app' onClick={() => { window.location.hash = `hot_product_gfyy` }}>返回</Button>
                    </div>
                </div>
                <div className='goods-label-let clearfix'>
                    <div className="floor-ppagi">
                        {
                            this.state.total == 0 ?
                                <p className="floor-ppagip">
                                    共{this.state.total}条记录
              </p> :
                                <p className="floor-ppagip">
                                    当前显示
                {this.state.pageSize * (this.state.page - 1) + 1}—
                {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                共{this.state.total}条记录
              </p>
                        }
                        <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
                    </div>
                </div>
            </div>
        )
    }
}

export default merchandiseList_zml;
